package com.gegao.chat_test;

import net.sf.json.JSONObject;
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.websocketx.*;
import org.jboss.netty.util.CharsetUtil;

public class WebSocketClientHandler extends SimpleChannelUpstreamHandler {
    private final WebSocketClientHandshaker handshaker;
    private final int threadId;
    private final int interval;

    public WebSocketClientHandler(WebSocketClientHandshaker handshaker, int threadId, int interval) {
        this.handshaker = handshaker;
        this.threadId = threadId;
        this.interval = interval;
    }


    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
        System.err.println("WebSocket Client disconnected!");
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws InterruptedException {
        Channel ch = ctx.getChannel();
        if (!handshaker.isHandshakeComplete()) {
            handshaker.finishHandshake(ch, (HttpResponse) e.getMessage());
            System.err.println("WebSocket Client connected!");
            return;
        }

        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) e.getMessage();
            throw new IllegalStateException("unexpected response (status=" + response.getStatus() + ", content="
                    + response.getContent().toString(CharsetUtil.UTF_8) + ')');
        }

        WebSocketFrame frame = (WebSocketFrame) e.getMessage();
        if (frame instanceof TextWebSocketFrame) {
            proMsgRecall(ctx.getChannel(), ((TextWebSocketFrame) frame).getText());
        } else if (frame instanceof PongWebSocketFrame) {
            System.err.println("WebSocket Client received pong");
        } else if (frame instanceof CloseWebSocketFrame) {
            System.err.println("WebSocket Client received closing");
            ch.close();
        } else if (frame instanceof PingWebSocketFrame) {
            System.err.println("WebSocket Client received ping, response with pong");
            ch.write(new PongWebSocketFrame(frame.getBinaryData()));
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        System.err.print("线程" + Thread.currentThread().getName() + "发生错误" + e.getCause());
        e.getChannel().close();
    }

    private void proMsgRecall(Channel channel, String json) throws InterruptedException {
        try {
            JSONObject jsonObject = JSONObject.fromObject(json);
            if (jsonObject.getString("method").equals("recallsendmessage")) {
                Thread.sleep(interval * 1000);
                int uid = (int) (1000+Math.random() * ClientTester.activityThread.get()-1);
                while (uid == 0 || uid == this.threadId) {
                    uid = (int) (1000+Math.random() * ClientTester.activityThread.get()-1);
                }
                String content = "{\"method\":\"sendmessage\",\"content\":{\"type\":\"TEXT\",\"text\":\"你好，朋友\"},\"uid\":" + threadId + ",\"touid\":" + uid + ",\"clientdate\":1452749048304}";
                channel.write(new TextWebSocketFrame(content));

            }
        } catch (Exception e) {
            return;
        }
    }
}
